package com.haojiang.mh.ui.activity

import android.content.Intent
import android.util.Log
import android.view.Gravity
import android.view.View
import androidx.core.view.GravityCompat
import androidx.fragment.app.Fragment
import com.google.android.material.navigation.NavigationView
import com.haojiang.mh.R
import com.haojiang.mh.cache.Const
import com.haojiang.mh.remote.enums.EConnect
import com.haojiang.mh.remote.event.DrawerEvent
import com.haojiang.mh.remote.ui.dialog.BleSingleDialogFrag
import com.haojiang.mh.remote.ui.dialog.SelectControlDialogFrag
import com.haojiang.mh.remote.ui.frag.ControlFrag
import com.haojiang.mh.remote.utils.BleUtil
import com.haojiang.mh.remote.utils.BleUtil.Companion.readGroupMap
import com.haojiang.mh.remote.utils.Util
import com.haojiang.mh.remote.utils.Util.Companion.getVersionName
import com.haojiang.mh.remote.utils.Util.Companion.initSound
import com.haojiang.mh.service.ble.BleHandle
import com.haojiang.mh.service.entity.BleNewData
import com.haojiang.mh.service.event.OneEvent
import com.haojiang.mh.ui.adapter.MainPagerAdapter
import com.haojiang.mh.ui.base.BaseActivity
import com.haojiang.mh.ui.fragment.*
import com.haojiang.mh.utils.ActManager
import com.haojiang.mh.utils.SpUtil
import com.haojiang.mh.widget.CommonDialog
import com.lx.permission.IPermissionCallback
import com.lx.permission.PermissionManager
import com.tencent.bugly.crashreport.CrashReport
import kotlinx.android.synthetic.main.activity_main.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * 主界面
 */
class MainActivity : BaseActivity() {

    companion object {
        const val TAB_CONTROL = 0
        const val TAB_ONE = 1
        const val TAB_TWO = 2
        const val TAB_THREE = 3
    }

    private val fragmentList = ArrayList<Fragment>()
    private var clickBackTimestamp = 0L
    private var wifiDialog: CommonDialog? = null

    //    private val onNavigationItemSelectedListener =
//        NavigationView.OnNavigationItemSelectedListener { menuItem ->
//            when (menuItem.itemId) {
////            R.id.navSearch -> {
////                drawerLayout.closeDrawers()
////                searchInterface();
//////                        showToast(this@MainActivity.getString(R.string.m_ble_not_connected))
////            }
//
//                R.id.navVersion -> {
//                    Util.showDialog(
//                        this@MainActivity,
//                        this@MainActivity.getString(R.string.f_version) + ":" + getVersionName()
//                    )
//                    drawerLayout.closeDrawers()
//                }
//            }
//
//            return@OnNavigationItemSelectedListener true
//        }
    private val onClickLisenter = object : View.OnClickListener {
        override fun onClick(v: View?) {
            v?.let {
                when (v.id) {
                    R.id.llSearch -> {
                        searchSurface()
                        drawerLayout.closeDrawers()
                    }
                    R.id.llSleepSetting -> {
                        redirectNoParam(SettingsActivity::class.java)
                        drawerLayout.closeDrawers()
                    }
                    R.id.llVersion -> {
                        Util.showDialog(
                            this@MainActivity,
                            this@MainActivity.getString(R.string.f_version) + ":" + getVersionName()
                        )
                        drawerLayout.closeDrawers()
                    }
//                    R.id.llLogout -> {
//                        ActManager.finishAll()
//                        System.exit(0)
//                    }
                }
            }
        }
    }

    private val mIPermissionCallback = IPermissionCallback {
        BleSingleDialogFrag.show(this@MainActivity)
//        ThreadUtils.asyn {
//            Thread.sleep(800)
//            ThreadUtils.ui {
//                BleSingleDialogFrag.show(activity!!)
//            }
//        }
    }

    private fun callSurface() {
        if (!Util.checkBleStatus(this@MainActivity)) return
        //申请权限
        PermissionManager.getInstance().setIPermissionCallback(mIPermissionCallback, 0)
        PermissionManager.getInstance().requestPermission(
            this@MainActivity,
            BleUtil.permissionArr
        )
    }

    private fun searchSurface() {
        if (BleUtil.ble.isBleEnable) {
            if (BleUtil.isDevConncted()) {
                if (BleUtil.lastConnect.connectType == EConnect.CONNECT_SINGLE.data) {                     //当前连接是单个设备连接
                    SelectControlDialogFrag.show(
                        this@MainActivity,
                        BleUtil.lastConnect.bleDeviceList.get(0).bleAddress
                    )
                }
//                else {
//                    choiceSelectGroupFrag(
//                        BleUtil.lastConnect.connectType,
//                        BleUtil.lastConnect.connectId
//                    )        //当前连接是组设备连接
//                }
            } else {
                callSurface()
            }
        }
    }

    override fun beforeSetContentView() {
        isSelfControlEvent = true
    }

    override fun getLayoutId() = R.layout.activity_main

    override fun getTitleName(): String? = null

    override fun initActivity() {
        ActManager.finishExcept(MainActivity::class.java)
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }
        CrashReport.setUserId(SpUtil[Const.DEVICE_WIFI_MAC, ""])

        //测试使用甜甜的设备
//        SpUtil.put(Const.DEVICE_WIFI_MAC,"D0BAE4E00179-D0BAE4E00178")
    }

    override fun initView() {

        aiv_tab_0.setOnClickListener { setTabSelectStatus(TAB_CONTROL) }
        aiv_tab_1.setOnClickListener { setTabSelectStatus(TAB_ONE) }
        aiv_tab_2.setOnClickListener { setTabSelectStatus(TAB_TWO) }
        aiv_tab_3.setOnClickListener { setTabSelectStatus(TAB_THREE) }

        fragmentList.clear()
        fragmentList.add(ControlFrag())
//        fragmentList.add(OneFragment())
//        fragmentList.add(TwoFragment())
//        fragmentList.add(ThreeFragment())
        vp_main.offscreenPageLimit = fragmentList.size
        val adapter = MainPagerAdapter(supportFragmentManager, fragmentList)
        vp_main.adapter = adapter

        setTabSelectStatus(TAB_CONTROL)                                //底部默认状态为遥控器界面

        initMain()
    }

    private fun initMain() {
//        leftNavigationView.setNavigationItemSelectedListener(onNavigationItemSelectedListener)
//        val leftLayoutParams = leftNavigationView.layoutParams
//        leftNavigationView.layoutParams = leftLayoutParams
        initSound()
        readGroupMap(this)  //读取组信息
        llSearch.setOnClickListener(onClickLisenter)
        llSleepSetting.setOnClickListener(onClickLisenter)
        llVersion.setOnClickListener(onClickLisenter)
//        llLogout.setOnClickListener(onClickLisenter)
    }

    override fun onDestroy() {
        EventBus.getDefault().unregister(this)
        BleHandle.instance.onMainDestroy()
        super.onDestroy()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (vp_main.currentItem <= fragmentList.size) {
            fragmentList[vp_main.currentItem].onActivityResult(requestCode, resultCode, data)
        }
    }

    /**
     * 设置选中状态
     */
    private fun setTabSelectStatus(index: Int) {
        if (vp_main.currentItem == index) return
        vp_main.setCurrentItem(index, false)
        aiv_tab_0.setImageResource(if (index != TAB_CONTROL) R.drawable.ic_tab_normal_0 else R.drawable.ic_tab_select_0)
        aiv_tab_1.setImageResource(if (index != TAB_ONE) R.drawable.ic_tab_normal_1 else R.drawable.ic_tab_select_1)
        aiv_tab_2.setImageResource(if (index != TAB_TWO) R.drawable.ic_tab_normal_2 else R.drawable.ic_tab_select_2)
        aiv_tab_3.setImageResource(if (index != TAB_THREE) R.drawable.ic_tab_normal_3 else R.drawable.ic_tab_select_3)
    }

    /**
     * 设备WiFi离线弹窗
     */
    private fun showWiFiOffDialog() {
        if (wifiDialog == null) {
            wifiDialog = CommonDialog.Builder(context, 2)
                .setTitle(getString(R.string.dialog_wifi_abnormal))
                .setContent(getString(R.string.dialog_wifi_abnormal_tip))
                .create()
        }
        if (wifiDialog != null && !wifiDialog!!.isShowing) {
            wifiDialog!!.show()
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, priority = 888)
    fun onReceiveEvent(event: OneEvent) {
        when (event.type) {
//            Const.JUMP_MAIN -> setTabSelectStatus(TAB_TWO)
            Const.JUMP_MAIN -> setTabSelectStatus(TAB_CONTROL)
            Const.DEVICE_WIFI_OFFLINE -> showWiFiOffDialog()
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onReceiveNewData(data: BleNewData) {
        // do nothing
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onDrawerEvent(event: DrawerEvent) {
        if (drawerLayout.isDrawerOpen(Gravity.LEFT)) {
            drawerLayout.closeDrawer(Gravity.LEFT);
        } else {
            drawerLayout.openDrawer(Gravity.LEFT);
        }
    }

    override fun onBackClick() {
        if ((System.currentTimeMillis() - clickBackTimestamp) > 2000) {//2秒内双击执行退出
            clickBackTimestamp = System.currentTimeMillis()
            showToast(R.string.tip_touch_again_to_exit)
        } else {
            ActManager.finishAll()
            System.exit(0)
        }
    }
}
